/* eslint-disable */
'use strict'

const express = require('express')
const router = express.Router()
const formidable = require('formidable');  
const fs = require('fs');
const log4js = require('log4js')
const logger = log4js.getLogger('upload')
const dateFormat = require('../utils/dateFormat')

const dbconnection = require('../config/database.js')
const insertInfo = (info, callback) => {
  dbconnection.execute('INSERT INTO INFOS SET ?', info, callback)
}
//引入node-xlsx解析excel模块  
const node_xlsx = require('node-xlsx'); 
const ExcelParse = (newPath, req) => {  
  let obj = node_xlsx.parse(newPath);  
  let excelObj = obj[0].data;//取得第一个excel表的数据
  excelObj.shift()//只取数据，忽略标题
  let sqlArr = new Array('name', 'mobile', 'birthday', 'left', 'right', 'flag')
  let infos = []
  excelObj.forEach((item, index) => {
    let info = {}
    item.push(req.session.flag) // 添加flag标示 用于区分哪个主账号客户
    item.forEach((e, i) => {
      let key = sqlArr[i]
      if (key === 'birthday') {
        let date = new Date(1900, 0, e - 1)//转换excel中的时间格式
        e = dateFormat(date, 'yyyy-MM-dd')
      }
      info[key] = e
      // info.set(key, e)
    })
    infos.push(info)
  })
  infos.forEach((info, index) => {
    insertInfo(info, (err, results, fields) => {
      if (err) {
        logger.error(err)
        return res.status(500).send({rtnMsg: '提交失败，服务器错误'})
      }
      logger.info(info)
      logger.info("成功解析excel 数据并且存进相应数据库！"); 
    })
  })
};
/* POST execl listing. */
router.post('/excel', (req, res, next) => {
  logger.info(req.session.uuid, req.cookies.uuid)
  if (req.session.uuid !== req.cookies.uuid || !req.session.uuid) {
    return res.send({rtnCode:'302', rtnMsg: '登录过期，请重新登录'});
  }
  let form = new formidable.IncomingForm();  
    form.encoding = 'utf-8';  
    // form.uploadDir = path.join(__dirname,'../public/upload/stuUpload/');  
    // form.keepExtensions = true;//保留后缀  
    // form.maxFieldsSize = 2*1024*1024;  
  form.parse(req, function(err, fields, files){  
    if(err){  
        logger.error('文件上传错误！');  
        return ;
    }
    let filename = files.file.name;
    // 对文件名进行处理，以应对上传同名文件的情况
    let nameArray = filename.split('.');  
    let type = nameArray[nameArray.length-1];  
    let name = '';  
    for(let i=0; i<nameArray.length-1; i++){  
        name = name + nameArray[i];  
    }  

    let date = new Date();  
    let time = '_' + date.getFullYear()+"_"+date.getMonth()+"_" +date.getDay()+"_" + date.getHours() +"_"+ date.getMinutes();  

    let avatarName = name + time +  '.' + type;  

    let newPath = form.uploadDir + avatarName ;  
    logger.info(newPath);  
    fs.renameSync(files.file.path, newPath);  //重命名  
    logger.info('重命名成功！');  
    //对excel文件进行解析读取数据  
    ExcelParse(newPath, req);    
  });  
  res.send({rtnCode:'000', rtnMsg: '上传成功，请去客户资料查看'})
});

module.exports = router;
